import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created with IntelliJ IDEA.
 * Description:文件的读取打开关闭
 * Author: WJW
 * Date: 2024-08-20
 * Time: 17:06
 */
public class IODemo1 {
    public static void main(String[] args) throws IOException {

        /*
        InputStream inputStream = null;
        try{
            //打开文件
            inputStream = new FileInputStream("./test.txt");
        }finally {
            //关闭文件
            inputStream.close();
        }
         */


        //一旦代码块出了try代码块，此时try自动帮我们调用inputStream的close
        //FileInputStream实现了Closeable接口的类

        try(InputStream inputStream = new FileInputStream("./test.txt")){
            //读文件
            while(true){
//                int b = inputStream.read();
//                if(b == -1){
//                    //文件读取完毕
//                    break;
//                }
//                //打印这个字节的数据
//                System.out.printf("%x ",b);

                //也可以一次读取若干个字节
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n == -1){
                    //文件读取完毕
                    break;
                }
                for (int i = 0; i < n; i++) {
                    System.out.printf("%x ",buffer[i]);
                }
            }
        }
    }
}
